#include <SerialFlash.h>
#include <main.h>
#include "context/guicontext.h"
#include "spi_port.h"

void fly_flash_init(void){
	printf("user flash init\n");
	SpiFlash_Init();
	printf("user flash init end\n");
}
uint32_t fy_flash_readid(void)
{
	return SpiFlash_ReadID();
}
void fy_flash_read(uint32_t address24, uint8_t* buffer, uint32_t length)
{
	//qspi_flash_quad_enable();
	//qspi_flash_buffer_read(buffer,address24,length);
	SpiFlash_Read(buffer,address24,length,0);
}

void fy_flash_readdma(uint32_t address24, uint8_t* buffer, uint32_t length)
{
	//qspi_flash_quad_enable();
	//qspi_flash_buffer_read(buffer,address24,length);
	//spi_flash_buffer_read(buffer,address24,length);
	SpiFlash_Read(buffer,address24,length,1);
}

void fy_flash_erase(){
	SpiFlash_ChipErase();

}
void fy_flash_erase_block(uint32_t start,uint32_t sizeOfBitmaps){
   SpiFlash_EraseSizeBlock(start,sizeOfBitmaps);
}
void fy_flash_page_write(uint32_t addr,uint8_t* data,uint32_t size){
	SpiFlash_Write_Page(data,addr,size);
}
char isReceivingData;
uint32_t fy_flash_isreceiveing(void)
{
	if(isReceivingData){
		isReceivingData = isDMA_isReceiveing();
	}
	return isReceivingData;
}

void fy_flash_waitreceive_done(void)
{
	
	if(isReceivingData){
		while(DMA_GetFlagStatus(SPIx_Rx_DMA_FLAG)!=SET);
		DMA_ClearFlag(SPIx_Rx_DMA_FLAG);

		DMA_ChannelEnable(SPIx_Tx_DMA_Channel, DISABLE);
		DMA_ChannelEnable(SPIx_Rx_DMA_Channel, DISABLE);
		SPI_I2S_DMAEnable(FLASH_SPI, SPI_I2S_DMA_TX, DISABLE);
		SPI_I2S_DMAEnable(FLASH_SPI, SPI_I2S_DMA_RX, DISABLE);
		FLASH_CS_HIGH();
	}
	isReceivingData = 0;
}
void fy_flash_dmainit(void)
{
  
}


const flythings_flash	m_flash ={
  .flash_init = fly_flash_init,
  .flash_deinit = fy_flash_dmainit,
  .flash_readdata = fy_flash_read,
  .flash_readdata_dma = fy_flash_readdma,
  .flash_wait_dma_end = fy_flash_waitreceive_done, 
  .flash_isreading = fy_flash_isreceiveing
};